<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>鸡兔同笼问题</title>

<style>

  .container {

    width: 60%;

    margin: 0 auto;

    background-color: lightblue;

    min-height: 220px;

  }

  h2 {

    text-align: center;

    padding-top: 10px;

  }

  p {

    width: 90%;

    margin: 0 auto;

    text-align: center;

  }

  input[type="number"] {

    box-sizing: border-box;

    width: 60px;

    margin: 5px;

  }

  .adjust-input {

    display: inline-block;

  }

  p#result {

    margin: 20px auto;

    height: 40px;

    width: 75%;

    padding: 20px;

    border: 1px dotted goldenrod;

    background-color: rgb(221, 220, 220);

    font-weight: bold;

    color: red; 

  }

</style>

</head>

<body>

<div class="container">

  <h2>循环解决鸡兔同笼问题</h2>

  <p>

    鸡兔同笼，鸡兔一共

    <span class="adjust-input">

      <input type="number" id="totalAnimals" value="35" min="1">

    </span>

    只。笼子里脚一共

    <span class="adjust-input">

      <input type="number" id="totalLegs" value="94" min="1">

    </span>

    只，请问分别有多少只鸡和兔？

  </p>

  <button onclick　="calculateRabbitsAndChickens()">计算</button>

  <p id="result"></p>

</div>



<script>

  function calculateRabbitsAndChickens() {

    let totalAnimals = parseInt(document.getElementById('totalAnimals').value);

    let totalLegs = parseInt(document.getElementById('totalLegs').value);



    // 假设每只鸡有2只脚，每只兔子有4只脚

    let chickens, rabbits;

    let hasSolution = false;



    // 循环计算鸡和兔子的数量

    for (chickens = 0; chickens <= totalAnimals; chickens++) {

      rabbits = totalAnimals - chickens;

      if ((chickens * 2 + rabbits * 4) === totalLegs) {

        hasSolution = true;

        break;

      }

    }



    // 显示结果

    let resultElement = document.getElementById('result');

    if (hasSolution) {

      resultElement.textContent = `分别有${chickens}只鸡和${rabbits}只兔子。`;

      resultElement.style.color = 'red'; // 有解时颜色为红色

    } else {

      resultElement.textContent = '无解';

      resultElement.style.color = 'black'; // 无解时颜色为黑色

    }

  }

</script>

</body>

</html>



